package Tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    private void start() throws IOException {
        System.out.println("服务器启动！");
        while(true) {
            //与客户端建立连接，至于内部是怎样建立连接的，是操作系统内核实现的，不是我们所考虑的范畴
            Socket cilentSocket = serverSocket.accept();
            processConnection(cilentSocket);
        }
    }

    private void processConnection(Socket cilentSocket) {
        System.out.printf("[%s:%d] 客户端上线！\n",cilentSocket.getInetAddress(),cilentSocket.getPort());
        try(InputStream inputStream = cilentSocket.getInputStream();
            OutputStream outputStream = cilentSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            while(true) {
                if(!scanner.hasNext()) {
                    System.out.printf("[%s:%d] 客户端下线！\n",cilentSocket.getInetAddress(),cilentSocket.getPort());
                    break;
                }
                //1.读取请求并解析
                String request = scanner.next();
                //2.计算响应
                String response = process(request);
                //3.返回计算出的响应
                //可以将其转化成byte数组然后返回
                //也可以将其通过PrintWriter打包一下返回
                PrintWriter writer = new PrintWriter(outputStream);
                //用println方法是为了方便客户端可以直接通过scanner.next()方法来直接获取到响应
                writer.println(response);
                writer.flush();
                System.out.printf("[%s:%d] : req = %s,res = %s\n",cilentSocket.getInetAddress(),cilentSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
